﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;
using System.Text.RegularExpressions;
using System.Security.Cryptography;


namespace Talk
{
    public partial class config : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if(Session["UserID"]==null)
            {
                Response.Redirect("/index.aspx");
                return;
            }
        }

        protected void submit_Click(object sender, EventArgs e)
        {
            errormsg.Text = "";
            if (Session["UserID"] == null)
            {
                errormsg.Text = "尚未登录！";
                return;
            }
            if(newpass.Text != newpass2.Text)
            {
                errormsg.Text = "两次密码输入不同！";
                return;
            }
            try
            {
                SHA1 sha1 = SHA1.Create();
                byte[] btmp = sha1.ComputeHash(System.Text.Encoding.Default.GetBytes(orgpass.Text));
                string orgp = BitConverter.ToString(btmp, 7, 7);
                SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["talkconn"].ConnectionString);
                conn.Open();
                string sql = "select Password from Users where UserID = '"
                    + Session["UserID"].ToString() + "'";
                SqlCommand cmd = new SqlCommand(sql, conn);
                SqlDataReader data = cmd.ExecuteReader();
                if (!data.HasRows)
                {
                    errormsg.Text = "用户不存在！";
                    conn.Close();
                    return;
                }
                data.Read();
                if (data["Password"].ToString() != orgp)
                {
                    errormsg.Text = "原始密码错误！";
                    conn.Close();
                    return;
                }
                data.Close();
                btmp = sha1.ComputeHash(System.Text.Encoding.Default.GetBytes(newpass.Text));
                string newp = BitConverter.ToString(btmp, 7, 7);
                cmd.CommandText = "update Users set Password = '" + newp + "' where UserID = '"
                    + Session["UserID"].ToString() + "'";
                cmd.ExecuteNonQuery();

                // TODO : 添加记录数据到Log表
                conn.Close();
                Session.Abandon();
                Response.Redirect("/index.aspx");
            }
            catch (System.Exception ex)
            {
                errormsg.Text = ex.Message;
            }
        }
    }
}
